// import { getUrlParam } from '@/common/js/utils.js';
// import gcoord from '@/common/js/gcoord.js';
import gcoord from '../../../common/js/gcoord.js';

export default {
  data() {
    return {
      startMarker: null, // 开始点的标记
      endMarker: null, // 结束点的标记
      editTip: null, // 地图信息窗体
      activeMarker: null, // 显示的点标记
      massObj: null, // 海量点对象
      markerlist: [],
      circleIsshow: false
    };
  },
  mounted() {

  },
  methods: {
    // 方法一、注册地图
    initMap() {
      this.mapInstance = new AMap.Map('mapSituation', {
        viewMode: "3D", // 使用3D视图
        zoomEnable: true, // 地图是否可缩放，默认值为true
        dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
        doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
        zoom: 14, //初始化地图级别
        center: [120.63862787231987, 31.26839516978756], // 初始化中心点坐标

        mapStyle: "amap://styles/normal", // 设置颜色底层
      });
      // 设置中心园
      if (this.circleIsshow) {
        var circle = new AMap.Circle({
          center: [120.63862787231987, 31.26839516978756],
          radius: 500, //半径
          borderWeight: 0,
          strokeColor: "#D2FFFF",
          strokeOpacity: 1,
          strokeWeight: 3,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          strokeStyle: 'solid',
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: '#1791fc',
          zIndex: 50,
        })
        this.mapInstance.add(circle);
      }
      let that=this
    
      // 自适应合适的范围
      // this.mapInstance.setFitView([ circle ])
    },
    pushMarker() {
      console.log('添加mark点')
      this.mapInstance.remove(this.markerlist)
      this.markerlist = []

      for (let i in this.originList) {
        this.markerlist.push(new AMap.Marker({
          position: new AMap.LngLat(this.originList[i].longitude, this.originList[i].latitude),
          offset: new AMap.Pixel(0, 0),
          zIndex: 9998,
          icon: new AMap.Icon({
            image: require('../../../assets/imgs/lookAround/marker.svg'),
            size: new AMap.Size(20, 25),  //图标大小
            imageSize: new AMap.Size(14, 20)
          })
        }))
      }
      this.markerlist.push(new AMap.Marker({
        position: new AMap.LngLat(120.63862787231987, 31.26839516978756),
        offset: new AMap.Pixel(0, 0),
        zIndex: 9999,
        icon: new AMap.Icon({
          image: require('../../../assets/imgs/lookAround/center_marker.svg'),
          size: new AMap.Size(22, 27),  //图标大小
          imageSize: new AMap.Size(16, 22)
        })
      }))
      this.mapInstance.add(this.markerlist);
    },
    // 方法二、热力图绘制
    initHotMaps(hotInfos) {
      const that = this;
      this.mapInstance.plugin(['AMap.HeatMap'], function () {
        //初始化HeatMap对象
        // eslint-disable-next-line no-undef
        that.heatmap = new AMap.HeatMap(that.mapInstance, {
          radius: 20, //给定半径
          opacity: [0, 0.8],
          gradient: {
            0.5: 'blue',
            0.65: 'rgb(117,211,248)',
            0.7: 'rgb(0, 255, 0)',
            0.9: '#ffea00',
            1.0: 'red'
          },

        });
        //设置数据集
        that.heatmap.setDataSet({
          data: hotInfos, // 此处填入你整理好的数据
          max: 712
        });
      });
    },

    // 方法三、清除地图的点标记和信息窗体
    clearMarker(type = 0) {
      // 删除之前的点标记
      if (type === 1) {
        this.massObj && this.massObj.setData([]);
      }
      this.activeMarker && this.mapInstance.remove([this.activeMarker]);
      this.startMarker && this.mapInstance.remove([this.startMarker]);
      this.endMarker && this.mapInstance.remove([this.endMarker]);
      this.routeLine && this.mapInstance.remove([this.routeLine]);
      // 删除之前的信息窗体
      if (this.editTip) {
        this.mapInstance.clearInfoWindow();
      }
    },

    // 方法四、地图定位放大（定位某个地区）
    setPosition(item) {
      this.clearMarker();
      this.selectArea = item;
      // 更新热力图分布
      if (this.heatmap !== null) {
        this.heatmap.setMap(null);
        this.initHotMaps(this.mapCopyInfos[this.activeIndex][this.$refs.selectArea.showIndex]);
      }
      if (!this.mapInstance) return;
      this.mapInstance.setZoom(13);
      this.mapInstance.setCenter(this.selectArea);
    },

    // 方法五、定位某个点
    openArea(item) {
      // 详情操作（企业需要）
      // this.getCompanyDetail(item);
      this.selectCompany = item;
      // this.showCompoy = false;
      // this.showLeft = false;
      this.clearMarker();
      const location = this.transCoord(item);
      // 创建标记点的实例
      const marker = this.initMarker(location);
      this.activeMarker = marker;
      let editTip = new AMap.InfoWindow({
        // eslint-disable-next-line no-undef
        offset: new AMap.Pixel(0, -45),
        isCustom: true
      });

      if (item.d2CorpName) {
        if (item.keyIndustries) {
          editTip.setContent(
            ` 
            <div class="amap-marker-info">
              <div class="amap-top">
                <div class="amap-top-left">
                <p class="body-name">${item.d2CorpName}</p>
                <div class="amap-second">
                </div>
                <div class="body-address">
                  <span>${item.distance}km |</span>
                  <span>${item.d2Dom}</span>
                  <span></span>
                </div>
                </div>
                <div class="amap-route" onclick="amapMarkerMoreEndFun()">
                </div>
              </div>
              <div class="body-label-right">
                <span>评分：</span>
                <span>${item.rating ? item.totalscore : ''} </span>
                <span>${item.rating ? item.rating : item.totalscore ? item.totalscore : '暂无'
            }</span>
              </div>
              <div class="amap-bottom">联系电话：${item.d2Tel ? item.d2Tel : '暂无'}</div>
            </div>
            `
          );
        } else {
          editTip.setContent(
            ` 
            <div class="amap-marker-info">
              <div class="amap-top">
                <div class="amap-top-left">
                <p class="body-name">${item.d2CorpName}</p>
                <div class="amap-second">
                </div>
                <div class="body-address">
                  <span>${item.distance}km |</span>
                  <span>${item.d2Dom}</span>
                  <span></span>
                </div>
                </div>
                <div class="amap-route" onclick="amapMarkerMoreEndFun()">
                </div>
              </div>
              <div class="body-label-right">
                <span>评分：</span>
                <span>${item.rating ? item.totalscore : ''} </span>
                <span class="score_${item.creditRate}">${item.rating ? item.rating : item.totalscore ? item.totalscore : ''
            }</span>
              <span class="level_${item.creditRate}">${item.creditRate ? item.creditRate : ''
            }</span>
              </div>
              <div class="amap-bottom">联系电话：${item.d2Tel ? item.d2Tel : '暂无'}</div>
            </div>
            `
          );
        }
      } else {
        editTip.setContent(
          ` 
          <div class="amap-marker-info">
            <div class="amap-top">
              <div class="amap-top-left">
              <p class="body-name">${item.creditName}</p>
              <div class="amap-second">
                <p class="amap-type">${item.creditType}</p>
              </div>
              <div class="body-address">
                <span>${item.distance}km |</span>
                <span>${item.address}</span>
                <span></span>
              </div>
              </div>
              <div class="amap-route" onclick="amapMarkerMoreEndFun()">
              </div>
              </div>
              <div class="amap-bottom">联系电话：${item.phone ? item.phone : '暂无'}</div>
              <div class="amap-bottom">邮箱地址：${item.email}</div>
          </div>
          `
        );
      }

      this.editTip = editTip;
      this.editTip.open(this.mapInstance, marker.getPosition());
      marker.setMap(this.mapInstance);
      this.mapInstance.setZoom(18);
      this.mapInstance.setCenter(location);
    },

    // 方法六、实例化点标记
    initMarker(param) {
      const marker = new AMap.Marker({
        // icon: '../../assets/images/poi-marker-red.png',
        icon: new AMap.Icon({
          // image: require('../../../assets/images/red_dian.png'),
          image: require('../../../assets/imgs/lookAround/A1.png'),
          // eslint-disable-next-line no-undef
          // size: new AMap.Size(24, 30)
          // size: isBig ? new AMap.Size(37, 47) : new AMap.Size(24, 30),
          // size: new AMap.Size(67, 67)
          imageSize: new AMap.Size(37, 46)
        }),
        position: new AMap.LngLat(param[0], param[1]),
        offset: new AMap.Pixel(-14, -38)
      });
      return marker;
    },

    /**
     * 方法七、绘制路线
     * @param {*} routeInfo 起始点信息
     */
    drawRoute(routeInfo) {
      const type = routeInfo.type;
      // 处理经纬度
      const startRoute = this.transCoord(routeInfo.startInfo);
      const endRoute = this.transCoord(routeInfo.endInfo);
      const that = this;
      const drivingOption = {
        policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
        ferry: 1, // 是否可以使用轮渡
        province: '苏' // 车牌省份的汉字缩写
      };

      // 构造路线导航类
      let driving = new AMap.Driving(drivingOption);
      // 根据起终点经纬度规划驾车导航路线
      driving.search(
        new AMap.LngLat(startRoute[0], startRoute[1]),
        new AMap.LngLat(endRoute[0], endRoute[1]),
        function (status, result) {
          // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            if (result.routes && result.routes.length) {
              // 绘制第一条路线，也可以按需求绘制其它几条路线
              drawRoute(result.routes[0], type);
            }
          }
        }
      );

      function drawRoute(route, type = 'car') {
        let path = parseRouteToPath(route);
        that.startMarker = new AMap.Marker({
          position: path[0],
          icon: new AMap.Icon({
            image:
              type === 'car'
                ? require('../../../assets/imgs/lookAround/A1.png')
                : require('../../../assets/imgs/lookAround/A1.png'),
            // eslint-disable-next-line no-undef
            // size: new AMap.Size(24, 30)
            // size: isBig ? new AMap.Size(37, 47) : new AMap.Size(24, 30),
            // size: new AMap.Size(67, 67)
            imageSize: new AMap.Size(37, 46)
          }),
          offset: new AMap.Pixel(-10, -30),
          map: that.mapInstance
        });

        that.endMarker = new AMap.Marker({
          position: path[path.length - 1],
          icon: new AMap.Icon({
            image: require('../../../assets/imgs/lookAround/A1.png'),
            // eslint-disable-next-line no-undef
            // size: new AMap.Size(24, 30)
            // size: isBig ? new AMap.Size(37, 47) : new AMap.Size(24, 30),
            // size: new AMap.Size(67, 67)
            imageSize: new AMap.Size(37, 46)
          }),
          offset: new AMap.Pixel(-10, -30),
          map: that.mapInstance
        });

        that.routeLine = new AMap.Polyline({
          path: path,
          isOutline: true,
          outlineColor: '#ffeeee',
          borderWeight: 2,
          strokeWeight: 5,
          strokeColor: 'red',
          lineJoin: 'round'
        });

        that.routeLine.setMap(that.mapInstance);
        // 调整视野达到最佳显示区域
        that.mapInstance.setFitView([that.startMarker, that.endMarker, that.routeLine]);
      }

      // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
      // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
      function parseRouteToPath(route) {
        let path = [];
        for (let i = 0, l = route.steps.length; i < l; i++) {
          let step = route.steps[i];
          for (let j = 0, n = step.path.length; j < n; j++) {
            path.push(step.path[j]);
          }
        }
        return path;
      }
    },

    // 海量点的处理
    seaMarkers(isBig = true) {
      this.isFirst = false;
      this.massObj && this.massObj.setData([]);
      const self = this;
      const markers = [];
      const style = [
        {
          url: require('../../../assets/imgs/lookAround/A1.png'),
          // eslint-disable-next-line no-undef
          // anchor: new AMap.Pixel(10, 10),
          // eslint-disable-next-line no-undef
          // anchor: new AMap.Pixel(11, 22),
          // size: new AMap.Size(37, 46),
          // size: new AMap.Size(37, 46)
          size: new AMap.Size(16, 22)
          // size: new AMap.Size(11, 11)
        }
      ];
      self.bankList.forEach(item => {
        if (item.latitude) {
          markers.push({
            lnglat: self.transCoord(item),
            id: item.companyId,
            name: item.d2CorpName ? item.d2CorpName : item.creditName,
            info: item
          });
        }
      });
      if (!self.massObj) {
        // eslint-disable-next-line no-undef
        self.massObj = new AMap.MassMarks(markers, {
          opacity: 0.8,
          zIndex: 221,
          cursor: 'pointer',
          style: style
        });
        // 绘制海量点
        const marker = new AMap.Marker({
          content: ' ',
          map: self.mapInstance
        });

        // 鼠标悬浮显示
        this.massObj.on('mouseover', function (e) {
          // console.log(11111111);
          marker.setPosition(e.data.lnglat);
          // 这边需要设置偏移量，不然label会不停的闪烁
          marker.setLabel({ content: e.data.name, offset: new AMap.Pixel(16, -6) });
        });

        this.massObj.on('mouseout', function (e) {
          // console.log(e.data.lnglat, 22222);
          marker.setPosition(e.data.lnglat);
          marker.setLabel({ content: '' });
        });
        // 增加click 事件
        this.massObj.on('click', function (e) {
          self.openArea(e.data.info);
        });
        this.massObj.setMap(self.mapInstance);
      } else {
        // console.log(markers, 'markers');
        self.massObj.setData(markers);
      }
      this.mapInstance.setZoom(16);
      if (this.region === '苏州市') {
        this.mapInstance.setCenter(['120.677934', '31.316626']);
      }
    },

    // 首次加载的特殊处理
    seaMarkers1(list, isBig = true) {
      // this.isFirst = false;
      this.massObj && this.massObj.setData([]);
      const self = this;
      const markers = [];
      const style = [
        {
          url: require('../../../assets/imgs/lookAround/A1.png'),
          // eslint-disable-next-line no-undef
          // anchor: new AMap.Pixel(10, 10),
          // eslint-disable-next-line no-undef
          // anchor: new AMap.Pixel(11, 22),
          // size: new AMap.Size(37, 46),
          // size: new AMap.Size(37, 46)
          size: new AMap.Size(16, 22)
          // size: new AMap.Size(11, 11)
        }
      ];
      list.forEach((item, index) => {
        if (item.latitude) {
          markers.push({
            lnglat: self.transCoord(item),
            id: item.corpList[0].corpKey,
            name: item.corpList[0].d2CorpName,
            info: item
          });
        }
      });
      if (!self.massObj) {
        // eslint-disable-next-line no-undef
        self.massObj = new AMap.MassMarks(markers, {
          opacity: 0.8,
          zIndex: 221,
          cursor: 'pointer',
          style: style
        });
        // 绘制海量点
        const marker = new AMap.Marker({
          content: ' ',
          map: self.mapInstance
        });

        // 鼠标悬浮显示
        this.massObj.on('mouseover', function (e) {
          // console.log(11111111);
          marker.setPosition(e.data.lnglat);
          // 这边需要设置偏移量，不然label会不停的闪烁
          marker.setLabel({ content: e.data.name, offset: new AMap.Pixel(16, -6) });
        });

        this.massObj.on('mouseout', function (e) {
          // console.log(e.data.lnglat, 22222);
          marker.setPosition(e.data.lnglat);
          marker.setLabel({ content: '' });
        });
        // 增加click 事件
        this.massObj.on('click', function (e) {
          // self.openArea(e.data.info);
        });
        this.massObj.setMap(self.mapInstance);
      } else {
        // console.log(markers, 'markers');
        self.massObj.setData(markers);
      }
      this.mapInstance.setZoom(12);
      const _this = this;
      setTimeout(() => {
        _this.mapInstance.setZoom(14);
      }, 2000);
    },

    // 坐标系转换
    transCoord(item) {
      const result = gcoord.transform(
        [item.longitude, item.latitude], // 经纬度坐标
        gcoord.BD09, // 当前坐标系
        gcoord.GCJ02 // 目标坐标系
      );
      return result;
    },

    // 坐标系转换
    transCoord1(item) {
      const result = gcoord.transform(
        [item[0], item[1]], // 经纬度坐标
        gcoord.GCJ02, // 目标坐标系
        gcoord.BD09 // 当前坐标系
      );
      return result;
    }
  }
};
